package com.ws.controller;


import com.alibaba.fastjson.JSONObject;
import com.ws.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("log")
public class FileController {

    @Value("${file.path}")
    private String filePath;

    @PostMapping("/file/upload")
    public Result fileUpload(@RequestParam("file")MultipartFile file) {

//        System.out.println(filePath);
//        System.out.println(file.getOriginalFilename());
        //将上传的文件名修改成唯一的不重复的文件名再存储到硬盘上
        String oldFileName = file.getOriginalFilename();
        //获取文件后缀
        String houZhui = oldFileName.substring(oldFileName.lastIndexOf("."));
        //拼接新字符串
        String newFilename = UUID.randomUUID()+houZhui;
        //将文件名和路径拼接，并实例化一个对象
        File file1 = new File(filePath+newFilename);
        System.out.println(filePath);

        JSONObject data = new JSONObject();
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.end(500,e.getMessage(),"上传失败");
        }
        data.put("url","/sp-service/v1/public/" + newFilename);
        data.put("fileName",newFilename);
        return Result.end(200,data,"上传成功");
    }

    @GetMapping("/file/delete")
    public Result deleteFile(@RequestParam("path") String path) {
        String fileName = path.substring(path.lastIndexOf("/") + 1);
        //完整路径
        String fullPath = filePath+fileName;
        File file = new File(fullPath);
        //检查文件是否存在 若存在删除
        if(file.exists()) {
            file.delete();
            return Result.end(200,"","删除文件成功");
        } else {
            return Result.end(500,"","文件删除失败");
        }
    }
}
